package com.caoustc.okhttplib.okhttp.utils

import com.caoustc.okhttplib.okhttp.OkHttpManager
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * Created by cz on 2018/6/14.
 */
class UrlHeadInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url()
        var host = url.host()
        val newUrl: String
        if (!host.startsWith("http")) {
            host = OkHttpManager.instance?.urlHead + host
            val scheme = url.scheme()
            val path = url.encodedPath()
            val query = url.encodedQuery()
            val sb = StringBuilder()
            newUrl = sb.append(scheme)
                .append(host).append(path).append("?").append(query).toString()
        } else {
            newUrl = host
        }
        val builder = request.newBuilder()
            .url(newUrl)
        return chain.proceed(builder.build())
    }
}